/*
 * Copyright (c) 2008-2009, Computational Crawling LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *    * Neither the name of Computational Crawling LP, 80legs, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.eightylegs.customer.sample;

import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.eightylegs.customer.Default80AppPropertyKeys;
import com.eightylegs.customer.I80App;

import org.w3c.dom.*;

import javax.xml.parsers.*;

/**
 * Class Sample80App.
 */
public class Sample80App implements I80App {
	
	/**
  	 * This should be set manually to the version name of the interface you have implemented.
  	 * 
  	 * @return the version name of the interface you have implemented
	 */
	public String getVersion() {
		return "80App_1.2";  // this must be set correctly or 80legs will not use your jar.
	}
	
	/**
	 * This initializes the Sample80App object. You should
	 * deserialize your data here if necessary and also store the
	 * Properties object if you are passing user parameter this way.
	 * 
	 * The properties file is not used in release 0.8, but it will be used
	 * in a future version and the customer will be allowed to pass user 
	 * settings to their code this way.
	 * 
	 * Your data sets will be uploaded to 80legs servers either 
	 * through the 80legs Portal or by using the 80legs Crawl API.
	 * 
	 * @param properties   This contains the user selected
	 *                     parameters from the web 
	 *                     portal or interface for this job
	 * @param data   The data that you passed into the 80legs web
	 *               portal.  You should deserialize that data here
	 *               and store anything necessary as a private object
	 *               in your I80App class.
	 */
	public void initialize( Properties properties, byte[] data ) {
		 
	}
	

	public Collection<String> parseLinks(byte[] documentContent, String url, Map<String, String> headers, Map<Default80AppPropertyKeys, Object> default80AppProperties, String statusCodeLine) {

		return null;
	}
	
	public byte[] processDocument(byte[] documentContent, String url, Map<String, String> headers, Map<Default80AppPropertyKeys, Object> default80AppProperties, String statusCodeLine) {
		 
		try {
			String pageString = byteArrayToString(documentContent, 0, documentContent.length);
			
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
				
			Element node = doc.createElement("listing");
			doc.appendChild(node);
			
			node = XML80app.addAttribute(node, "id", "naf\\['products'\\] = '(.*)'", pageString);
			node = XML80app.addAttribute(node, "name", "omni_prod_name= '(.*?)\\';", pageString);
			node = XML80app.addAttribute(node, "description_small", "<div class=\"tabArea1\"><h2>([\\s\\S]*?)</h2>", pageString);
			node = XML80app.addAttribute(node, "description_large", "<div class=\"tabArea1\">([\\s\\S]*?)</div>", pageString);
			node = XML80app.addAttribute(node, "manufacturer_name", "href=\"/brand/(.*?)\"", pageString);
			//node = XML80app.addAttribute(node, "manufacturer_model", "", pageString);
			//node = XML80app.addAttribute(node, "manufacturer_part_num", "", pageString);
			//node = XML80app.addAttribute(node, "barcode", "", pageString);
			node = XML80app.addAttribute(node, "sku", "<p class\"productSKU\">([\\s\\S]*?)</sku>", pageString);
			node = XML80app.addAttribute(node, "category_primary", "naf\\['subsection1'\\] = \"(.*)\"", pageString);
			node = XML80app.addAttribute(node, "category_secondary", "naf\\['subsection2'\\] = \"(.*)\"", pageString);
			node = XML80app.addAttribute(node, "category_tertiary", "naf\\['subsection3'\\] = \"(.*)\"", pageString);
			//node = XML80app.addAttribute(node, "weight", "", pageString);
			//node = XML80app.addAttribute(node, "online_only", "", pageString);
			node = XML80app.addAttribute(node, "buy_url", "<form .*? action=\"(.*?)\"", pageString);
			//node = XML80app.addAttribute(node, "qty", "", pageString);
			node = XML80app.addAttribute(node, "price", "<li class=\"price\">[\\s\\S]*?\\$(.*?)</li>", pageString);
			node = XML80app.addAttribute(node, "price", "<li class=\"price\">[\\s\\S]*?\\$(.*?) - .*?</li>", pageString);
			node = XML80app.addAttribute(node, "currency_code", "<input type=\"hidden\" name=\"currency\" value=\"(.*?)\"", pageString);
			
			Pattern p = Pattern.compile("<select id=\"prodType\"[\\s\\S]*?</select>");
			Matcher m = p.matcher(pageString);
			if (m.find()) {
				String optionsString = m.group();
				Element options = doc.createElement("options");
				node.appendChild(options);
				options = XML80app.addChildren(doc, options, "option", new String[]{"color", "size"}, "<option title=\"(.*?)\".*?>.*?(xxxs|xxs|xs|s|m|l|xl|xxl|xxxl) ", optionsString);				
			}
			
			Element images_large = doc.createElement("images_large");
			node.appendChild(images_large);
			images_large = XML80app.addChildren(doc, images_large, "image", new String[]{"url"}, "'(/zoom/.*?)'", pageString);				
						
			Element images_small = doc.createElement("images_small");
			node.appendChild(images_small);
			images_small = XML80app.addChildren(doc, images_small, "image", new String[]{"url"}, "'(/media/.*?)'", pageString);		

			return XML80app.generateXML(doc).getBytes();
		}
		
		catch ( Exception e ) {
			//return e.getMessage().getBytes();
			return null;
		}
	}

	public static String byteArrayToString(byte[] b, int byteStart, int numBytes) throws Exception
	{
		return new String (b, byteStart, numBytes, "UTF-8");
	}

}
